/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MainClasses;
import MainClasses.Event.*;
import java.util.*;
import java.io.*;

/**
 *
 * @author andrewcutler
 */
public class CourseManager {
    
    private ArrayList<Course> courses;
    
    public CourseManager()
    {
        courses = new ArrayList<Course>();
    }
    
    public void purge()
    {
        this.saveEvents(main.getPrefs());
        courses = new ArrayList<Course>();
    }
    public ArrayList<Course> getCourses()
    {
        return courses;
    }
    
    public void addCourse(Course c)
    {
        courses.remove(c);
        courses.add(c);
    }
    
    public ArrayList<Event> getAllEvents()
    {
        ArrayList<Event> temp = new ArrayList<Event>();
        
        for(Course c : courses)
        {
            for(Event e : c.getEvents())
            {
                temp.add(e);
            }
        }
        return temp;
    }
    

    @Override
    public String toString()
    {
        String returnString = "";
        
        for(int i = 0; i < courses.size(); i++)
        {
            returnString += "Class: " + courses.get(i).getCourseName() + "\n";
            ArrayList<Event> assignments = courses.get(i).getEvents();
            for(int j = 0; j < assignments.size(); j++)
            {
                returnString += "\t - Assignment: (Due " +assignments.get(j).getEndDate().toString(MyDate.FORMAT_1, "-") + ") "+ assignments.get(j).getName() + "\n";
            }
        }
        
        return returnString;
    }
    
    public Course findCourse(int id)
    {
        for(Course c : courses)
        {
            if(c.getCourseID() == id)
                return c;
        }
        return null;
    }
    
    public void sort()
    {
        ArrayList<Course> temp = new ArrayList<Course> ();
        for(Course c : courses)
        {
            int indexLowest = 0;
            for(int i = 0; i < courses.size(); i++)
            {
                if(courses.get(indexLowest).getPeriod() > courses.get(i).getPeriod())
                {
                    indexLowest = i;
                }
            }
            Course f = courses.get(indexLowest);
            courses.remove(f);
            courses.add(0, f);
        }
        
        courses = temp;
    }
    
    public void loadAll(Preferences prefs)
    {
        loadEvents(prefs);
        loadChecks(prefs);
    }
    
    public void loadChecks(Preferences prefs)
    {
        DataInputStream in;
        Course currentCourse = new Course();
        Event currentEvent = new SchoolEvent(Event.CLASSWORK);
        String currentLine = "";
        try
        {
            File file = new File(prefs.getCheckedName());
            in = new DataInputStream(new FileInputStream(file));
            while(in.available() > 0)
            {
                currentLine = in.readLine();
                if(currentLine.contains("<course"))
                {  
                    String id = currentLine.substring(currentLine.indexOf("=")+1, currentLine.indexOf(">"));
                
                    System.out.println(id);
                    
                    currentCourse = findCourse(Integer.parseInt(id));
                }
                else if(currentCourse != null && currentLine.contains("<assignment>"))
                {
                    String id = in.readLine();
                    id = id.substring(id.indexOf("<id>")+4, id.indexOf("</id>"));
                    for(Event e : currentCourse.getEvents())
                    {
                        if(e.equal(id))
                        {
                            currentEvent = e;
                        }
                    }
                    
                    if(currentEvent instanceof CheckableEvent)
                    {
                        String checked = in.readLine();
                        boolean bool = Boolean.parseBoolean(checked.substring(checked.indexOf("<checked>") + 9, checked.indexOf("</checked>")));
                        
                        ((CheckableEvent)currentEvent).set(bool);
                    }
                }
                else if(currentLine.contains("</course>"))
                {
                    currentCourse = null;
                }
            }
        }
        catch(Exception e)
        {
            main.error(e);
            return;
        }
        
        
    }
    
    public void loadEvents(Preferences prefs)
    {
        DataInputStream in;
        Course user = main.getUserCourse();
        Event currentEvent = new UserEvent();
        String currentLine = "";
        
        try
        {
            File file = new File(prefs.getUserFileName());
            in = new DataInputStream(new FileInputStream(file));
            
            if(!in.readLine().equals("<user events>"))
                    throw new Exception("FILE CORRUPTED");
            while(in.available() > 0)
            {
                currentLine = in.readLine();
                if(currentLine.contains("<event type=4>"))
                {
                    currentEvent = new UserEvent();
                }
                else if(currentLine.contains("<event type=5"))
                {
                    currentEvent = new UserCheckEvent();
                    currentLine = in.readLine();
                    ((CheckableEvent)currentEvent).set(Boolean.parseBoolean(currentLine.substring(currentLine.indexOf("<checked>")+9, currentLine.indexOf("</checked>"))));
                }
                if(currentEvent != null)
                {
                    currentLine = in.readLine();
                    MyDate startDate = MyDate.parseDate(currentLine.substring(currentLine.indexOf("<begin>")+7, currentLine.indexOf("</begin>")), MyDate.FORMAT_2);
                    currentLine = in.readLine();
                    MyDate endDate = MyDate.parseDate(currentLine.substring(currentLine.indexOf("<end>")+5, currentLine.indexOf("</end>")), MyDate.FORMAT_2);
                    currentLine = in.readLine();
                    String name = currentLine.substring(currentLine.indexOf("<name>")+6, currentLine.indexOf("</name>"));
                    currentLine = in.readLine();
                    String description = currentLine.substring(currentLine.indexOf("<description>")+13, currentLine.indexOf("</description>"));
                    currentEvent.setStartDate(startDate);
                    currentEvent.setEndDate(endDate);
                    currentEvent.setName(name);
                    currentEvent.setDescription(description);
                    main.getUserCourse().addEvent(currentEvent);
                    currentEvent = null;
                }
            }
            
        }
        catch(Exception e)
        {
            main.error(e);
        }
        
        
    }
    
    
    public void saveChecks(Preferences prefs)
    {
        PrintWriter out;
        
        try
        {
            out = new PrintWriter(new FileWriter(new File(prefs.getCheckedName())));
            for(Course c : courses)
            {
                out.println("<course id=" + c.getCourseID()+">");
                for(Event a : c.getEvents())
                {
                    out.println("\t\t<assignment>");
                    out.println("\t\t\t<id>" + a.getUniqueID() + "</id>");
                    if(a instanceof CheckableEvent)
                        out.println("\t\t\t<checked>" + ((CheckableEvent)a).isChecked() + "</checked>");
                    out.println("\t\t</assignment>");
                }
                out.println("</course>");
            }
            out.close();
            
        }
        catch(IOException e)
        {
            main.error(e);
        }
    }
    
    public void saveEvents(Preferences prefs)
    {
        PrintWriter out;
        try
        {
            out = new PrintWriter(new FileWriter(new File(prefs.getUserFileName())));
            out.println("<user events>");
            
            for(Event e : main.getUserCourse().getEvents())
            {
                System.out.println(e);
                out.println("\t<event type=" + e.getType() + ">");
                if(e instanceof CheckableEvent)
                    out.println("\t\t<checked>" + ((CheckableEvent)e).getChecked() + "</checked>");
                out.println("\t\t<begin>" + e.getStartDate().toString(MyDate.FORMAT_2, "-") + "</begin>");
                out.println("\t\t<end>"   + e.getEndDate().toString(MyDate.FORMAT_2, "-")   + "</end>");
                out.println("\t\t<name>"  + e.getName() + "</name>");
                out.println("\t\t<description>" + Event.removeEscapeSequences(e.getDescription()) + "</description>");
                out.println("\t</event>");
            }
            
            out.println("</user events>");
            out.close();
        }
        catch(Exception e)
        {
            main.error(e);
        }
    }
    
    

}
